package com.ddd.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * Created by zhouxj6112 on 2019/12/13.
 */
@Slf4j
@Component
public class AccessLogFilter extends ZuulFilter {

    @Override
    public String filterType() {
        // 过滤器的类型
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        // zuul 组件默认的 response filter 的 order 是 1000（因为zuul的FilterConstants.SEND_RESPONSE_FILTER_ORDER
        // 常量就是1000），所以我们的 response 过滤器的 order要在 FilterConstants.SEND_RESPONSE_FILTER_ORDER 之前，否则不起作用。
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        // 是否启用当前的过滤器
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        // 从上下文中取出 PreRequestFilter 设置的请求时间戳
        Long startTime = (Long) context.get("startTime");
        String uri = request.getRequestURI();
        long duration = System.currentTimeMillis() - startTime;
        Long userId = (Long) context.get("userId");

        // 从网关通过的请求都会打印这条日志记录: uri + duration
        String method = request.getMethod();
        String info = "uri: " + uri + ", duration: " + duration + "ms, method: " + method + ", userid: " + userId;
        try {
            String parameters = queryParameters(request);
            if (parameters != null) {
                info += "\n请求参数: " + parameters;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info(info);

        return null;
    }

    private String queryParameters(HttpServletRequest request) throws IOException {
        String method = request.getMethod().toUpperCase();
        if (method.equals("GET")) {
            Map<String, String[]> map = request.getParameterMap();
            return JSONObject.toJSONString(map);
        } else if (method.equals("POST")) {
            String contentType = request.getHeader("content-type");
            if (contentType.contains("application/json")) {
                InputStream is = request.getInputStream();
                return StreamUtils.copyToString(is, Charset.forName("utf-8"));
            } else {
                // 上传文件之类的,暂时不管
            }
        }
        return null;
    }

}
